package com.im.app.authConfig;

import com.alibaba.fastjson.JSON;
import com.im.app.model.User;
import com.im.app.processor.ChatMessageProcessor;
import com.im.app.utils.Response;
import com.im.app.utils.StringUtils;
import org.jim.core.cache.redis.JedisTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Configuration
public class WebHandlerInterceptor implements HandlerInterceptor
{
    private static Logger logger = LoggerFactory.getLogger(WebHandlerInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)throws Exception
    {

        //如果是预检请求，手动加上请求状态200
        if (request.getMethod().equals(RequestMethod.OPTIONS.name())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }
        response.setCharacterEncoding("utf-8");
        HandlerMethod handlerMethod = null;
        try {
            handlerMethod = (HandlerMethod)handler;
        } catch (Exception e){
            response.setStatus(HttpStatus.NOT_FOUND.value());
            return false;
        }
        Method method = handlerMethod.getMethod();
        RequireLogin requireLogin = method.getAnnotation(RequireLogin.class);
        if (requireLogin == null) {
            return true;
        }
        final String token = request.getHeader("token");
        if(StringUtils.isEmpty(token)) {
            response.getWriter().write(JSON.toJSONString(Response.makeErrRsp("token为空!")));
            return false;
        }
        User user = JedisTemplate.me().get(token, User.class);
        if (user == null) {
            response.getWriter().write(JSON.toJSONString(Response.makeErrRsp("登录过期,请重新登录！")));
            return false;
        }
        user.setToken(token);
        request.setAttribute("currentUser", user);
        return true;
    }

    public boolean postHandle(HttpServletRequest request, HttpServletResponse rsp, Object handler)throws Exception{
        return false;
    }

    public boolean afterCompletion(HttpServletRequest request, HttpServletResponse rsp, Object handler)throws Exception{
        return false;
    }

}
